<template>
  <div class="settlement">
    <loading v-if="isLoading"></loading>
    <div v-else>
      <!--  -->
      <div
        class="address"
        v-if="!(shopType == 'storeAdd' || shopType == 'shopAdd')"
        @click="popupType = 'address', showPopup = true"
      >
        <div class="right-icon">
          <icon name="location-o" size="1.5rem" color="#283C79"></icon>
        </div>
        <div class="address-info">
          <p v-if="selectedAddress.name">
            <span class="name">{{selectedAddress.name}}</span>
            <span class="phone">{{selectedAddress.phone}}</span>
          </p>
          <p class="detail" v-if="selectedAddress.name">{{selectedAddress.fullAddress}}</p>
          <p v-if="!selectedAddress.name" @click="goToAddAddress">先新增一个收货地址</p>
        </div>
        <div class="left-icon">
          <icon name="arrow"></icon>
        </div>
      </div>

      <div class="cart">
        <div class="product-list">
          <div class="product-item" v-for="(item,index) in cartList" :key="index">
            <product-item :cover="staticHost + item.goodsImg">
              <div class="product-info" slot="product-item">
                <div class="product-name">{{item.goodsName}}</div>
                <div class="product-spec">
                  <p>{{item.size}}</p>
                </div>
                <div class="product-price">
                  <p>
                    <span>￥{{item.presentPrice}}</span>
                    <span class="delete" v-if="item.price">￥{{item.price}}</span>
                  </p>
                  <span>x {{item.number}}</span>
                </div>
              </div>
            </product-item>
          </div>
        </div>

        <div class="item-info">
          <p>买家备注：</p>
          <p class="buy-remark">
            <input v-model="remark" type="text" placeholder="这里可填写对本次交易的说明" />
          </p>
        </div>
        <div class="item-info">
          <p>商品金额：</p>
          <p class="product-amount">￥{{totalPrice}}</p>
        </div>
        <div class="item-info" v-if="!(shopType == 'storeAdd' || shopType == 'shopAdd')">
          <p>
            快递费用：
            <!-- <span class="tip">1箱起快递就免邮</span> -->
          </p>
          <p class="delivery-fee">￥{{deliverMoney}}</p>
        </div>
        <div class="total">
          <span>共{{cartList.length}}件</span>
          <span>小计：</span>
          <span v-if="shopType == 'storeAdd' || shopType == 'shopAdd'">￥{{totalPrice}}</span>
          <span
            v-if="!(shopType == 'storeAdd' || shopType == 'shopAdd')"
          >￥{{(Number(totalPrice) + Number(deliverMoney)).toFixed(2)}}</span>
        </div>
      </div>

      <div class="buyer-info">
        <div class="item-info">
          <p>可用货款：</p>
          <p>￥{{agentInfo.goods_money}}</p>
        </div>
        <div class="item-info">
          <p>可用余额：</p>
          <p>￥{{agentInfo.balance}}</p>
        </div>
      </div>

      <div class="submit">
        <van-button
          type="info"
          size="large"
          v-if="shopType == 'storeAdd' || shopType == 'shopAdd'"
          @click="submitAdd"
        :disabled="isSubmitting">{{isSubmitting ? '正在提交' : '确定进货'}}</van-button>
        <!-- <van-button type="info" size="large" v-if="shopType == 'carryAdd'" @click="submitAdd">确定提货</van-button> -->
        <van-button type="info" size="large" v-else @click="submitAdd"  :disabled="isSubmitting">{{isSubmitting ? '正在提交' : '确定提货'}}</van-button>
      </div>

      <div class="cancel" v-if="!(shopType == 'storeAdd')">
        <van-button plain type="danger" size="large" @click="clearStorage"  :disabled="isSubmitting">清空重选</van-button>
        <!-- <van-button plain type="danger" size="large">清空重选</van-button> -->
      </div>
    </div>

    <popup :show="showPopup" @onCancel="onCancel">
      <div class="popup-adress" v-if="popupType == 'address'">
        <div class="header">选择地址</div>
        <radio-group v-model="radio" @change="onRadioChange">
          <div class="address-list">
            <list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
              <div
                class="address-item popup-address-item"
                v-for="(item,index) in addressList"
                :key="index"
              >
                <div @click="radio = index">
                  <div class="address-info">
                    <p>
                      <span class="name">{{item.name}}</span>
                      <span class="phone">{{item.phone}}</span>
                    </p>
                    <p class="detail">{{item.fullAddress}}</p>
                  </div>
                  <van-radio :name="index" />
                </div>
              </div>
            </list>
          </div>
        </radio-group>
      </div>
    </popup>
  </div>
</template>
<script>
import productItem from "../components/product_item.vue";
import { Icon, Button, Toast, Dialog, List, RadioGroup, Radio } from "vant";
import { mapState } from "vuex";
import loading from "../components/loading.vue";
import { staticHost } from "../service/HOST.js";
import popup from "../components/popup.vue";
import _ from "lodash";

export default {
  components: {
    productItem,
    Icon,
    vanButton: Button,
    loading,
    popup,
    RadioGroup,
    vanRadio: Radio,
    List
  },
  data() {
    return {
      // storeAdd（云仓进货-结算）, shopAdd（商城进货-结算）, carryAdd（云仓提货-结算）, normalAdd（直购-结算）
      shopType: this.$route.query.shopType || "normalAdd",
      staticHost,
      agentInfo: {},
      cartList: [],
      isLoading: true,
      addressList: [],
      selectedAddress: {},
      pageNumber: 1,
      pageSize: 10,
      loading: false,
      finished: false,
      remark: "",
      totalPrice: 0,
      deliverMoney: 0,
      showPopup: false,
      popupType: "",
      radio: 0,
      isSubmitting: false,
    };
  },
  computed: {
    ...mapState({
      userInfo: state => state.login_module.userinfo,
      countAlias: "userInfo"
    })
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      // 只允许from的路径来源
      const path = [
        "/my_store_add_goods",
        "/product_browse",
        "/my_cloud_store",
        "/home/shopping_cart"
      ];

      if (path.indexOf(from.path) == -1) {
        vm.$router.replace({
          path: "/login"
        });

        return false;
      }
    });
  },
  async mounted() {
    // 进货结算
    if (this.shopType == "shopAdd") {
      let data = {
        title: "进货结算"
      };
      this.$store.commit("setNavInfo", data);
      document.title = data.title + " - TIMELESS 分销商城";
      this.cartList = JSON.parse(localStorage.getItem("addGoods"));

      // 云仓单个商品进货结算
    } else if (this.shopType == "storeAdd") {
      let data = {
        title: "进货结算"
      };
      this.$store.commit("setNavInfo", data);
      document.title = data.title + " - TIMELESS 分销商城";
      this.cartList = JSON.parse(localStorage.getItem("addStore"));

      // 提货结算
    } else if (this.shopType == "carryAdd") {
      let data = {
        title: "提货结算"
      };
      this.$store.commit("setNavInfo", data);
      document.title = data.title + " - TIMELESS 分销商城";
      this.cartList = JSON.parse(localStorage.getItem("addCarry"));
      await this.getAddressList();

      // 直购结算
    } else if (this.shopType == "normalAdd") {
      let data = {
        title: "直购结算"
      };
      this.$store.commit("setNavInfo", data);
      document.title = data.title + " - TIMELESS 分销商城";
      this.cartList = JSON.parse(localStorage.getItem("addCart"));
      await this.getAddressList();
    }

    // 获取用户余额和货款
    await Promise.all([this.getAgentInfo()]).then(res => {
      this.isLoading = false;
    });

    // 计算总额 和 快递费
    this.totalPrice = 0;
    this.deliverMoney = 0;
    this.cartList.forEach(item => {
      // 提货不计算总额
      if (this.shopType != "carryAdd") {
        this.totalPrice += item.presentPrice * item.number;
      }

      // 提货和直购时 计算快递费
      if (this.shopType == "carryAdd" || this.shopType == "normalAdd") {
        if (item.expressFee == 1 && item.postage) {
          this.deliverMoney += item.postage;
        }
      }
    });

    this.totalPrice = this.totalPrice.toFixed(2);
    this.deliverMoney = this.deliverMoney.toFixed(2);
  },
  beforeDestroy() {
    localStorage.removeItem("addStore");
  },
  methods: {
    // 提交订单
    async submitAdd() {
      let query = {};
      if(this.isSubmitting){
        Toast('正在提交，请稍等')
        return false
      }

      // Toast('正在提交，请稍等')
      this.isSubmitting = true

      new Promise((resolve, reject) => {
        // 进货结算
        if (this.shopType == "storeAdd" || this.shopType == "shopAdd") {
          query = {};

          let cartList = _.cloneDeep(this.cartList);
          cartList.forEach(item => {
            item.num = item.number;
            item.goodsId = item.id ? item.id : item.goodsId;
            delete item.id;
            delete item.number;
            delete item.createBy;
            delete item.createDate;
            delete item.expressFee;
            // delete item.goodsImg;
            // delete item.goodsName;
            delete item.price;
            delete item.isDelete;
            delete item.isDirect;
            delete item.postage;
            delete item.status;
            delete item.size;
          });

          // console.log(cartList);

          return this.$http
            .post(this.$urls.YCJHDD, {
              data: JSON.stringify(cartList),
              orderMoney: this.totalPrice,
              remark: this.remark
            })
            .then(res => {
              if (res.data.code == 200) {
                Toast.success(res.data.msg);

                let data = res.data.data
                if(data.orderInfo.state == 0){
                  Toast("订单尚未支付");
                }

                // 清空购物车缓存
                localStorage.removeItem("addGoods");

                resolve(res.data.data);
              } else {
                Toast(res.data.msg);
                reject(0);
              }
            })
            .catch(err => {});

          // 提货结算 和 直购结算
        } else if (
          this.shopType == "carryAdd" ||
          this.shopType == "normalAdd"
        ) {
          if (!this.selectedAddress.name) {
            Toast("请先新增一个收货地址");
            return false;
          }

          query = {};

          let cartList = _.cloneDeep(this.cartList);
          console.log(this.cartList);
          cartList.forEach(item => {
            item.num = item.number;
            item.goodsId = item.id ? item.id : item.goodsId;
            delete item.id;
            delete item.number;
            delete item.createBy;
            delete item.createDate;
            delete item.expressFee;
            // delete item.goodsImg;
            // delete item.goodsName;
            delete item.price;
            delete item.isDelete;
            delete item.isDirect;
            delete item.postage;
            delete item.status;
            delete item.orderBonus;
            delete item.categoryId;
            delete item.size;
            delete item.ticket;
            delete item.stockOutNum;
          });

          // 提货结算 和 直购结算 不同的接口
          let url = null;
          if (this.shopType == "carryAdd") {
            url = this.$urls.THJSDD;
          } else if (this.shopType == "normalAdd") {
            url = this.$urls.ZGGWC;
          }

          return this.$http
            .post(url, {
              data: JSON.stringify(cartList),
              address: this.selectedAddress.id,
              orderMoney: this.totalPrice,
              transportMoney: this.deliverMoney,
              remark: this.remark
            })
            .then(res => {
              if (res.data.code == 200) {
                Toast.success(res.data.msg);

                // 清空购物车缓存
                if (this.shopType == "carryAdd") {
                  localStorage.removeItem("addCarry");
                } else if (this.shopType == "normalAdd") {
                  localStorage.removeItem("addCart");
                }

                resolve(res.data.data);
              } else {
                Toast(res.data.msg);
                reject(0);
              }
            })
            .catch(err => {});
        }
      })
        .then(res => {
          console.log("处理结果：", res);
          this.isSubmitting = false

          if (res) {
            // localStorage.setItem("orderDetail", JSON.stringify(res));

            // 下订单成功就跳转到订单详情
            this.$router.replace({
              path: "/order_detail",
              query: {
                orderNumber: res.orderInfo.orderNumber,
                orderType: this.shopType
              }
            });
          }
        })
        .catch(err => {
          console.log("结算错误：", err);
        });
    },
    clearStorage() {
      if(this.isSubmitting){
        Toast('正在提交，请稍等')
        return false
      }

      Dialog.confirm({
        title: "确认清空吗",
        message: ""
      })
        .then(() => {
          // 进货结算
          if (this.shopType == "shopAdd") {
            localStorage.removeItem("addGoods");
            // 提货结算
          } else if (this.shopType == "carryAdd") {
            localStorage.removeItem("addCarry");
            // 直购结算
          } else if (this.shopType == "normalAdd") {
            localStorage.removeItem("addCart");
          }

          // 退回
          this.$router.go(-1);
        })
        .catch(() => {
          // on cancel
        });
    },
    onRadioChange(value) {
      // console.log(value)
      this.selectedAddress = this.addressList[value];
    },
    onLoad() {
      return this.$http
        .post(this.$urls.HQDZLB, {
          uid: this.userInfo.id,
          // uid: 2,
          pageNumber: this.pageNumber,
          pageSize: this.pageSize
        })
        .then(res => {
          if (res.data.code == 200) {
            let data = res.data.data;
            data.forEach(item => {
              item.fullAddress =
                item.provinceName +
                " " +
                item.cityName +
                " " +
                item.countryName +
                " " +
                item.address;
            });
            this.addressList = this.addressList.concat(data);
            this.selectedAddress = this.addressList[0];

            this.pageNumber++;

            this.loading = false;
          } else if (res.data.code == 300) {
            this.loading = false;
            this.finished = true;
          }
        });
    },
    // 获取地址列表
    getAddressList() {
      return this.$http
        .post(this.$urls.HQDZLB, {
          uid: this.userInfo.id,
          // uid: 2,
          pageNumber: this.pageNumber,
          pageSize: this.pageSize
        })
        .then(res => {
          if (res.data.code == 200) {
            let data = res.data.data;
            data.forEach(item => {
              item.fullAddress =
                item.provinceName +
                " " +
                item.cityName +
                " " +
                item.countryName +
                " " +
                item.address;
            });
            this.addressList = this.addressList.concat(data);
            this.selectedAddress = this.addressList[0];

            this.pageNumber++;

            this.loading = false;
          } else if (res.data.code == 300) {
            this.loading = false;
            this.finished = true;
          }
        });
    },
    // 获取用户信息
    getAgentInfo() {
      return this.$http
        .post(this.$urls.DLXQ, {
          id: this.userInfo.id
        })
        .then(res => {
          if (res.data.code == 200) {
            let data = res.data.data;
            this.agentInfo = data;
          }
        });
    },
    goToAddAddress() {
      this.$router.replace({
        path: "/add_address"
      });
    },
    onCancel() {
      this.showPopup = false;
    }
  }
};
</script>
<style scoped>
.address,
.cart {
  margin: 10px;
  padding: 10px 15px;
  background-color: #fff;
  border-radius: 10px;
}

.buyer-info {
  margin: 10px;
  padding: 0 15px;
  background-color: #fff;
  border-radius: 10px;
}

.address {
  display: flex;
  align-items: center;
}

.address-info {
  flex: 1;
}

.address-info .detail {
  word-wrap: wrap;
  word-break: break-all;
}

.address-info .name {
  font-size: 1rem;
  color: var(--Emphasize-font);
  padding-right: 10px;
}

.right-icon {
  padding-right: 10px;
  display: flex;
  align-items: center;
}

.left-icon {
  display: flex;
  align-items: center;
}

.product-info {
  padding: 10px;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  color: var(--Emphasize-font);
}

.product-spec {
  font-size: 0.9rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-price {
  display: flex;
  justify-content: space-between;
  /* color: var(--money-up); */
}

.delete {
  padding-left: 5px;
  font-size: 0.8rem;
  text-decoration: line-through;
  /* color: #868387; */
}

.product-price > p > span:first-child {
  color: var(--money-up);
}
.item-info {
  display: flex;
  justify-content: space-between;
  padding: 10px;
}

.item-info > p:first-child {
  color: var(--Emphasize-font);
  min-width: 80px;
}

.buy-remark {
  flex: 1;
}

.buy-remark input {
  border: 0;
  width: 100%;
}

::-webkit-input-placeholder {
  /* WebKit browsers */
  direction: rtl;
}

.total {
  margin-top: 5px;
  border-top: 1px solid var(--line-between-color);
  padding-right: 10px;
  padding-top: 10px;
  text-align: right;
}

.total span {
  padding-left: 5px;
}

.total span:last-child {
  color: var(--money-up);
}

.tip {
  color: var(--money-up);
}

.popup-address-item > div {
  padding: 10px 15px;
  display: flex;
}

.popup-adress {
  max-height: 435px;
}

.popup-adress .header {
  padding: 10px 15px;
  text-align: center;
  border-bottom: 1px solid var(--line-between-color);
}
</style>